package cn.sunxyz.spider.downloader;



import cn.sunxyz.spider.Page;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * Created by yangrd on 2018/6/1
 **/
public class ProxyDownloader implements Downloader {

    private Downloader downloader;

    private List<String> list = Arrays.asList(
            "39.137.69.8:8080",
            "39.137.69.8:80",
            "39.137.69.10:80",
            "39.137.69.10:8080",
            "39.137.69.6:80",
            "39.137.77.66:8080",
            "39.137.77.66:80",
            "221.130.253.135:8090",
            "39.137.69.9:80",
            "39.137.77.68:8080",
            "39.137.77.67:80",
            "39.137.77.67:8080",
            "39.137.69.7:80",
            "101.4.136.34:81",
            "222.33.192.238:8118"
    );

    public ProxyDownloader(Downloader downloader) {
        this.downloader = downloader;
    }

    @Override
    public Page download(String request) {
        dynamicIp();
        return downloader.download(request);
    }

    Random random = new Random();

    private void dynamicIp() {
        synchronized (this){
            int index = random.nextInt(list.size()-1);
            String[] proxy = list.get(index).split(":");
            String ip = proxy[0];
            String port = proxy[1];
            System.getProperties().setProperty("http.proxyHost", ip);
            System.getProperties().setProperty("http.proxyPort", port);
        }
    }
}
